
#include "user.h"

static uint32_t ms10_callback_time  = 0;

static uint32_t event_feedback_time = 0;
static uint8_t  event_feedback_enable = 0;

static uint32_t led_blink_time = 0;

beep beep1;
extern_event event;

static void led_callback( uint32_t blink_time );
static void beep_callback( beep* bp );

void system_init(void){
	beep_open(0);
	led_open(0);
	feedback(0);
	
	beep1.open = 0;
  beep1.open_time = 100; 			//打开时间默认为100ms
	beep1.old_time = 0;
	
	event.flag = EVENT_NONE;
	event.continue_time = 0;
	
	ms10_callback_time = HAL_GetTick();
	
}

//led回调函数
static void led_callback( uint32_t blink_time ) {  //10ms回调
	  static uint32_t old_time = 0;
	
	  if( blink_time<=0 ){
			led_open(1);
			return;
		}
	
		if( HAL_GetTick()-old_time<=blink_time ){
			led_open(0);
		}else if( HAL_GetTick()-old_time<=2*blink_time ){
			led_open(1);
		}else{			
			old_time = HAL_GetTick();
		}
}

//beep回调函数
static void beep_callback( beep* bp  ){    //10ms回调
	if( bp->open ){
		beep_open(1);   //打开蜂鸣器
		if( HAL_GetTick()-bp->old_time > bp->open_time ){
			bp->open = 0;
			beep_open(0); //关闭蜂鸣器
		}
	}
}

//反馈回调
static void feedback_callback( void ){
	if( event_feedback_enable ){
		feedback(1);   //低电平反馈
		if( HAL_GetTick()-event_feedback_time>100 ){
			feedback(0);
			event_feedback_enable = 0;
		}
	}
}

//外部事件处理回调函数
static void event_callback( void ){
	switch( event.flag ){
		case EVENT_RISING:
			if( HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_6)==GPIO_PIN_SET ){
				if( HAL_GetTick()-event.low_old_time>20 ){ //持续20ms为低电平
					event_feedback_enable = 1;    //相机反馈
					event_feedback_time = HAL_GetTick();
					open_beep();
					event.flag = EVENT_NONE;
				}
			}else{  //电平无效
				event.flag = EVENT_NONE;
			}
			break;
		case EVENT_FALLING:
		case EVENT_LOW:
	  case EVENT_NONE:
		case EVENT_HIGH:
		case EVENT_END:
		default: 
			break;
	}
	
	if( EVENT_HIGH==event.flag ){
		event.flag = EVENT_NONE;
		//event_feedback_enable = 1;    //相机反馈
	}
}

void event_ipt(void){
	event.flag = EVENT_RISING;
	event.low_old_time = HAL_GetTick();
}

void open_beep(void){
	beep1.open = 1;
	beep1.old_time = HAL_GetTick();
	beep1.open_time = 100;
}

void app( void ){
	system_init();
	while(1){
			if( HAL_GetTick()-ms10_callback_time>=10 ){
				led_callback(100);
				feedback_callback();
				beep_callback(&beep1);
				ms10_callback_time = HAL_GetTick();
			}
			event_callback();
	}
}
